package com.liuyongqi.accountbook;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private MyAdapter adapter;
    private NotesDBHelper helper;
    private SQLiteDatabase db;
    private Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.lv_data);
        helper = new NotesDBHelper(this);//调用getWritableDatabase或者getReadableDatabase产生数据库

        db = helper.getReadableDatabase();
        selectDB();


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {//每个item设置一个点击事件
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                cursor.moveToPosition(position);
                Intent intent = new Intent(MainActivity.this, Detail.class);
                intent.putExtra(NotesDBHelper.ID, cursor.getInt(cursor.getColumnIndex(NotesDBHelper.ID)));
                intent.putExtra(NotesDBHelper.TYPE, cursor.getString(cursor.getColumnIndex(NotesDBHelper.TYPE)));
                intent.putExtra(NotesDBHelper.MONEY, cursor.getString(cursor.getColumnIndex(NotesDBHelper.MONEY)));
                intent.putExtra(NotesDBHelper.PATH, cursor.getString(cursor.getColumnIndex(NotesDBHelper.PATH)));
                startActivityForResult(intent,100);
            }
        });
    }
    public void selectDB() {
        cursor = db.query(NotesDBHelper.TABLE_NAME, null, null, null,null, null, null);
        adapter = new MyAdapter(this, cursor);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        selectDB();
    }


    public void select(View view) {

        Intent intent = new Intent(MainActivity.this, Select.class);
        startActivityForResult(intent,100);
    }

    public void start(View view) {

        Intent intent = new Intent(MainActivity.this, Account.class);
        startActivityForResult(intent,100);
    }
    public void install (View view) {
        Intent intent = new Intent(this, SetUp.class);
        startActivity(intent);
    }
}